import { CONVERT_TYPE } from "../convertable/Consts"
import { BaseUtil } from "../convertable/BaseUtil"

export class ParamUtil extends BaseUtil {
  /**
   * @param {Object} params 表单参数
   * @example
   * (params) : const params = {
   *       bii_name: "11",
   *       bodyDtoList: [],
   *       __view: false,
   *       __edit: false,
   *       ext13: "",
   *       ext2: ""
   *     }
   * (include type) :
   *             new ParamUtil(params)
   *             .setType(CONVERT_TYPE.C)
   *             .excludeTypeKey(["bodyDtoList"]) // 不需要转换的key
   *             // 只转换需要的key
   *             // ** include()方法无需build **
   *             .include([
   *                 "bii_name"
   *               ])
   *
   * (exclude type) :
   *       const pb = new ParamUtil(params)
   *       .setType(CONVERT_TYPE.S)
   *       .excludeKey(["__view","__edit"]) // 排除掉无用key
   *       .excludeTypeKey(["bodyDtoList"]) // 不需要转换的key
   *       .build()
   */
  constructor(params) {
    super()
    this.params = params || {}

    this.type = CONVERT_TYPE.C
  }

  /**
   * 排处掉form key并转换form key的形式 <br/>
   * 默认转换为驼峰形式[CONVERT_TYPE.C] <br/>
   * 设置转换形式 setType()
   * @returns {{}}
   */
  build() {
    const { params, excludeKeys = [], excludeTypeKeys = [] } = this
    const resultObj = {}
    Object.entries(params).map(([key, value]) => {
      if (!excludeKeys.includes(key)) {
        resultObj[key] = value
      }

      if (resultObj[key] && !excludeTypeKeys.includes(key)) {
        const typedKey = this._toTypedKey(key)
        resultObj[typedKey] = value
      }
    })

    return resultObj
  }

  /**
   * @param {Array} includeKeys 转换包含的form key
   * @returns {{}}
   */
  include(includeKeys = []) {
    const { params, excludeTypeKeys = [] } = this
    const resultObj = {}
    Object.entries(params).map(([key, value]) => {
      if (includeKeys.includes(key)) {
        resultObj[key] = value
      }
      // 如果包含key, 且没有被排处转换的key
      if (resultObj[key] && !excludeTypeKeys.includes(key)) {
        const typedKey = this._toTypedKey(key)

        // delete the key that's been converted
        delete resultObj[key]
        resultObj[typedKey] = value
      }
    })

    return resultObj
  }
}
